<template>
    <page-wrapper>
        <table-search @search="search(1)" @reset="reset()">
            <template slot="form">
                <form-item label="">
                    <a-input v-model.trim="form.notifyName" placeholder="通知名称" />
                </form-item>
                <form-item label="">
                    <a-input v-model.trim="form.notifyCode" placeholder="通知编码" />
                </form-item>
                <form-item label="">
                    <a-select v-model="form.alarmType" style="width:150px;" allowClear placeholder="请选择报警类型">
                        <a-select-option :value="level.value" v-for="(level,index) in alarmTypes" :key="index">{{level.label}}</a-select-option>
                    </a-select>
                </form-item>
            </template>
            <template slot="extra">
                <a-button class="filter-item" type="primary" :disabled="hasPerm(['notice:rule:add'])" icon="plus" @click="addInfo()">新增规则</a-button>
                <a-button
                    class="filter-item btn_space"
                    type="danger"
                    @click="remove()"
                    :disabled="!selectionBox.length || hasPerm(['notice:rule:remove'])"
                    icon="delete"
                    >删除</a-button
                >
            </template>
        </table-search>
        <div class="table_scroll">
            <table-list
                :loading="loading"
                :columns="columns"
                rowKey="ruleId"
                :pagination="pagination"
                :selection="selection"
                :data="list"
                :scroll="{x:1400}"
            >
                <template slot="alarmType" slot-scope="{ text }">
                    <field-tag
                        :value="text.alarmType"
                        type="value"
                        showType="label"
                        :key="'alarm-'+text.ruleId"
                        :data="alarmTypes"
                    ></field-tag>
                </template>
                <template slot="templateCode" slot-scope="{ text }">
                    <field-tag
                        :value="text.templateCode"
                        type="templateCode"
                        showType="templateName"
                        :key="'templateCode-'+text.ruleId"
                        :data="templateList"
                    ></field-tag>
                </template>
                <template slot="relaUser" slot-scope="{ text }">
                    <p class="user_list" v-html="filterUsers(text.relaUser,userList)"></p>
                </template>
                <!-- <template slot="relationField" slot-scope="{ text }">
                    <field-tag
                        :value="text.relationField"
                        type="parameterCode"
                        :key="'parameterCode-'+text.ruleId"
                        showType="parameterName"
                        :data="paramList"
                    ></field-tag>
                </template> -->
                <!-- <template slot="open" slot-scope="{ text }">
                    <a-switch
                        checked-children="开启"
                        un-checked-children="关闭"
                        :key="text.ruleId"
                        :default-checked="text.open==1 ? true : false"
                        @change="onSwitchStatus(text)"
                    />
                </template> -->
                <template slot="action" slot-scope="{ text }">
                    <!-- <a-button size="small" type="primary" class="btn_space" :disabled="hasPerm(['notice:rule:update'])" @click="bindDevice(text)">关联设备</a-button> -->
                    <a-button size="small" type="primary" class="btn_space" :disabled="hasPerm(['notice:rule:update'])" @click="addInfo(text)">编辑</a-button>
                    <a-button size="small" type="danger" class="btn_space" :disabled="hasPerm(['notice:rule:remove'])" @click="remove(text)">删除</a-button>
                </template>
            </table-list>
        </div>

        <template v-if="isShowInfo">
            <rule-info :info="itemInfo" :paramList="paramList" :userList="userList" :templateList="templateList" @cancel="isShowInfo = false" @submit="submit" />
        </template>

        <template v-if="isShowDevice">
            <device-transfer :info="itemInfo" @cancel="isShowDevice = false" @submit="getDevices"></device-transfer>
        </template>
        
    </page-wrapper>
</template>
<script>
import table from '@/mixins/table';
import { columns } from './columns';
import RuleInfo from './components/info';
import {alarmTypes} from './dictionary'
import {remoteList,updateInfo,deleteInfo} from '@/api/notice/rule'
import templateApi from '@/api/notice/template'
import paramApi from '@/api/notice/param'
import userApi from '@/api/system/user'
import DeviceTransfer from '@/views/components/deviceTransfer'

export default {
    name: 'UserList',
    mixins: [table],
    components: {
        RuleInfo,
        DeviceTransfer
    },
    data() {
        let originForm = {
            notifyName: null,
            notifyCode: null,
            alarmType: undefined,
        };
        return {
            originForm,
            alarmTypes,
            form: {
                ...originForm
            },
            columns,
            itemInfo: null,
            isShowInfo: false,
            paramList:[],
            templateList:[],
            userList:[],
            isShowDevice:false,
        };
    },
    async created(){
        await this.getSource();
        this.search(1)
    },
    methods: {
        async search(page) {
            try {
                this.loading = true;
                if(page){
                    this.form.page = page
                }
                this.list = []
                let res = await remoteList(this.form);
                let { list, total } = res.data;
                this.list = list;
                this.total = total;
                this.selectionBox = []
            } finally {
                this.loading = false;
            }
        },
        //删除
        remove(item = '') {
            this.$confirm({
                title: '提示',
                content: '确定要删除规则？',
                okText: '确定',
                cancelText: '取消',
                onOk:async ()=>{
                    try{
                        let ids=[];
                        if (item) {
                            ids = [item.ruleId];
                        } else {
                            let selectionBox = this.selectionBox;
                            selectionBox.map(async item => {
                                ids.push(item.ruleId);
                            });
                        }
                        await deleteInfo({ids});
                        this.$message.success('删除成功!');
                        this.search(1);
                    }catch(err){

                    }
                },
                onCancel() {}
            });
        },
        //是否开启
        async onSwitchStatus(item) {
            try {
                let { open } = item;
                item.open = open==1 ? 0 : 1;
                this.loading = true;
                await updateInfo(item);
                this.$message.success('操作成功!');
            } catch (err) {
                let { open } = item;
                item.open = open ? 0 : 1;
            } finally {
                this.loading = false;
            }
        },
        //显示添加用户
        addInfo(item = {}) {
            this.isShowInfo = true;
            this.itemInfo = item;
        },
        submit() {
            this.isShowInfo = false;
            this.itemInfo = {}
            this.search(1);
        },
        //关联设备
        bindDevice(item){
            this.isShowDevice = true;
            let {deviceCode} = item;
            this.itemInfo = item;
            if(deviceCode){
                this.itemInfo.devices = JSON.parse(deviceCode)
            }
        },
        //设备提交之后处理
        async getDevices(e){
            try{
                this.loading = true
                let {devices} = e;
                let deviceCode = '';
                if(devices && devices.length){
                    deviceCode = JSON.stringify(devices)
                }
                this.itemInfo.deviceCode = deviceCode;
                await updateInfo(this.itemInfo);
                this.search(1)
            }finally{
                this.loading = false;
                this.isShowDevice = false;
                this.itemInfo = {};
            }
        },
        // 获取数据
       async getSource(){
           let form = {
               page:1,
               size:1000
           }
        //    let paramResult = await paramApi.remoteList(form);
           let templateResult = await templateApi.remoteList(form);
           let userResult = await userApi.remoteList(form)
        //    this.paramList = paramResult.data.list;
           this.templateList = templateResult.data.list;
           this.userList = userResult.data.list;
       },
       filterUsers(text,userList){
            if(!userList || !userList.length || !text) return '';
            let userIds = text.split(',');
            let userBox = [];
            userIds.map(user=>{
                let userInfo = userList.find(item=>item.userId==user);
                userBox.push(`<span>${userInfo.userName}</span>`)
            })
            return userBox.join('，')
        }
    },
    filters:{
        
    }
};
</script>
<style lang="scss" scoped>
.user_list{
    span{
        word-break: break-all;
    }
}
</style>